/**
 * @author cwoodard
 */
    dojo.require('dojo.parser');
    dojo.require('dojo.data.ItemFileReadStore');
    dojo.require('dojo.data.ItemFileWriteStore');
    dojo.require("dojox.grid.compat._grid.edit");
    dojo.require('dojox.grid.DataGrid');
    dojo.require('dijit.form.Button');
    dojo.require("dijit.Dialog");
    dojo.require("dijit.form.TextBox");
    dojo.require("dijit.form.SimpleTextarea");
    dojo.require("dijit.form.Textarea");
    dojo.require("dijit.form.FilteringSelect");

    // build and initialize arrays for ItemFileWriteStores
    var catererData = {
        identifier: "id",
		label: 'id',
        items: caterersMasterArray
    };

    var menusData = {
        identifier: 'id',
		label: 'id',
        items: []
    };
    
    var menusLayout = [
        { field: "namecell", name: "Menu", width:"200px" },
        { field: "pricecell", name: "Price", width:"200px" }
    ];

    // select no caterer at start
    var iSelectedCaterer = -1;
    var iSelectedMenu = -1;

    var idx = 0;

    // stuff needed to define catalog grid
    var caterersArray = {
        identifier: "id",
		label: 'ID',
		items: caterersMasterArray
    };
    var caterersLayout = [
        { field: "id", name:"ID", hidden:true },
        { field: "namecell", name: "Caterer", width:"200px" },
        { field: "loccell", name: "Location", width:"200px" }
    ];
    var caterersQuery = { id: '*'};
    var menusQuery = { id: '*'};

    var caterersGrid = null;
    var menusGrid = null;

//////////////////////////////////////////////////////////////////////////////////////////////////////////
    function formatCatererNamecell( caterer )
    {
        var str = '<strong><span style="font-size:12pt">' + caterer.name + '</span></strong><br>';
        str = str + 'Phone:<strong>' + caterer.phone + '</strong><br>';
        str = str + 'Fax:<strong>' + caterer.fax + '</strong><br>';
        str = str + 'Email:<strong>' + caterer.email + '</strong><br>';
        return str;
    }

    function formatCatererLoccell( caterer )
    {
        var str = '<strong><span style="font-size:12pt">' + caterer.address + '</span></strong><br>';
        str = str + '<span style="font-size:10pt">' + caterer.city + ', ';
        str = str + caterer.state + ' ' + caterer.zip + '</span>';
        return str;
    }

    function getCatererForId(id)
    {
        var numCaterers = caterersMasterArray.length;
        var ii;
        for( ii=0; ii < numCaterers; ii++ )
        {
            if( caterersMasterArray[ii].id == id )
                return caterersMasterArray[ii];
        }
        return null;
    }

    function getMenusForCaterer(id)
    {
        var numCaterers = menusMasterArray.length;
        var ii;
        for( ii=0; ii < numCaterers; ii++ )
        {
            if( menusMasterArray[ii].caterer_id == id )
                return menusMasterArray[ii].menus;
        }
        return null;
    }
    
    function catererSelected(e)
    {
        var i = e.rowIndex;
        var item = caterersGrid.getItem(i);
        var id = caterersGrid.store.getValues(item, 'id');
        var caterer = getCatererForId(id);
        if(caterer)
        {
            var menus = getMenusForCaterer(id);
            if(menus)
            {
                menusData.items = menus;
                menusGrid.store.close();
                menusGrid.setStore(new dojo.data.ItemFileWriteStore({data:menusData}));
            }
            else
            {
                menusData.items = [];
                menusGrid.store.close();
                menusGrid.setStore(new dojo.data.ItemFileWriteStore({data:menusData}));
            }
        }
    }
    
    function getSelectedCaterer()
    {
        var items = caterersGrid.selection.getSelected();
        if(items.length<1) return null;
        return items[0];
    }

    function getNewCatererId()
    {
        var max_id = -1;
        var ii;
        for( ii=0; ii < menusMasterArray.length; ii++ )
        {
            if( max_id < menusMasterArray[ii].caterer_id )
                max_id = menusMasterArray[ii].caterer_id;
        }
        return max_id + 1;
    }
    
    function showNewCatererForm()
    {
        // get form
        var catererForm = dijit.byId("catererForm");

        catererForm.execute=addNewCaterer;
        
        // make sure contents are empty
        dijit.byId("caterer_name").attr('value','');
        dijit.byId("caterer_address").attr('value','');
        dijit.byId("caterer_city").attr('value','');
        dijit.byId("caterer_state").attr('value','');
        dijit.byId("caterer_zip").attr('value','');
        dijit.byId("caterer_phone").attr('value','');
        dijit.byId("caterer_fax").attr('value','');
        dijit.byId("caterer_email").attr('value','');

        catererForm.show();
    }
    
    function showEditCatererForm()
    {
        // get selected caterer
        // get caterer form
        var catererForm = dijit.byId("catererForm");

        catererForm.execute=updateCaterer;

        // fill caterer fields with field values from selected caterer
        var caterer = getSelectedCaterer();
        if(null == caterer)
        {
            alert('You must select a caterer first');
            return;
        }

        var caterer_name = caterersGrid.store.getValues(caterer, 'name');
        var caterer_address = caterersGrid.store.getValues(caterer, 'address');
        var caterer_city = caterersGrid.store.getValues(caterer, 'city');
        var caterer_state = caterersGrid.store.getValues(caterer, 'state');
        var caterer_zip = caterersGrid.store.getValues(caterer, 'zip');
        var caterer_phone = caterersGrid.store.getValues(caterer, 'phone');
        var caterer_fax = caterersGrid.store.getValues(caterer, 'fax');
        var caterer_email = caterersGrid.store.getValues(caterer, 'email');

        dijit.byId("caterer_name").attr('value',caterer_name);
        dijit.byId("caterer_address").attr('value',caterer_address);
        dijit.byId("caterer_city").attr('value',caterer_city);
        dijit.byId("caterer_state").attr('value',caterer_state);
        dijit.byId("caterer_zip").attr('value',caterer_zip);
        dijit.byId("caterer_phone").attr('value',caterer_phone);
        dijit.byId("caterer_fax").attr('value',caterer_fax);
        dijit.byId("caterer_email").attr('value',caterer_email);
        
        catererForm.show();
    }

    function addNewCaterer()
    {
        // generate new id for caterer - run thru caterers list and get max id
        // and add 1.
        var caterer_id = getNewCatererId();

        var caterer = {};

        caterer.id = caterer_id;
        caterer.name = dijit.byId('caterer_name').attr('value');
        caterer.address = dijit.byId('caterer_address').attr('value');
        caterer.city = dijit.byId('caterer_city').attr('value');
        caterer.state = dijit.byId('caterer_state').attr('value');
        caterer.zip = dijit.byId('caterer_zip').attr('value');
        caterer.phone = dijit.byId('caterer_phone').attr('value');
        caterer.fax = dijit.byId('caterer_fax').attr('value');
        caterer.email = dijit.byId('caterer_email').attr('value');

        caterer.namecell = formatCatererNamecell( caterer );
        caterer.loccell = formatCatererLoccell( caterer );
        
        // now that we have this, let's add it to the caterer array
        // do it using the caterersStore.
        var caterersGrid = dijit.byId('caterersGrid');
        caterersGrid.store.newItem( caterer );

        // okay, now that we've added a new caterer we need
        // to make a new empty entry in the menusMasterArray structure with
        // the right caterer id and all.
        var new_menu_group = {caterer_id:caterer_id,menus:[]};
        menusMasterArray.push( new_menu_group );

        // now select this caterer and empty out the menus grid
        var caterer_idx = findCatererIdxById( caterer_id );
        caterersGrid.selection.select( caterer_idx );

        menusData.items = new_menu_group.menus;
        menusGrid.store.close();
        menusGrid.setStore(new dojo.data.ItemFileWriteStore({data:menusData}));
    }

    function findCatererIdxById( caterer_id )
    {
        var ii;
        for( ii=0; ii < caterersMasterArray.length; ii++ )
        {
            if( caterer_id == caterersMasterArray[ii].id )
                return ii;
        }
        return -1;
    }

    function findCatererById( caterer_id )
    {
        var ii;
        for( ii=0; ii < caterersMasterArray.length; ii++ )
        {
            if( caterer_id == caterersMasterArray[ii].id )
                return caterersMasterArray[ii];
        }
        return null;
    }

    function updateCaterer( caterer_id )
    {
        var caterer = getSelectedCaterer();

        // now we can access via catterer.name, etc.
        var caterer_name = dijit.byId('caterer_name').attr('value');
        var caterer_address = dijit.byId('caterer_address').attr('value');
        var caterer_city = dijit.byId('caterer_city').attr('value');
        var caterer_state = dijit.byId('caterer_state').attr('value');
        var caterer_zip = dijit.byId('caterer_zip').attr('value');
        var caterer_phone = dijit.byId('caterer_phone').attr('value');
        var caterer_fax = dijit.byId('caterer_fax').attr('value');
        var caterer_email = dijit.byId('caterer_email').attr('value');

        caterersGrid.store.setValue( caterer, 'name', caterer_name );
        caterersGrid.store.setValue( caterer, 'address', caterer_address );
        caterersGrid.store.setValue( caterer, 'city', caterer_city );
        caterersGrid.store.setValue( caterer, 'state', caterer_state );
        caterersGrid.store.setValue( caterer, 'zip', caterer_zip );
        caterersGrid.store.setValue( caterer, 'phone', caterer_phone );
        caterersGrid.store.setValue( caterer, 'fax', caterer_fax );
        caterersGrid.store.setValue( caterer, 'email', caterer_email );

        var caterer_namecell = formatCatererNamecell( caterer );
        var caterer_loccell = formatCatererLoccell( caterer );
        
        caterersGrid.store.setValue( caterer, 'namecell', caterer_namecell );
        caterersGrid.store.setValue( caterer, 'loccell', caterer_loccell );
        
        caterersGrid.store.fetch();
        caterersGrid.update();
    }

    function removeMenusForCaterer(caterer_id)
    {
        for( var ii=0; ii < menusMasterArray.length; ii++ )
        {
            if( caterer_id == menusMasterArray[ii].caterer_id )
            {
                menusMasterArray.splice( ii, 1 );
                menusData.items = [];
                menusGrid.store.close();
                menusGrid.setStore(new dojo.data.ItemFileWriteStore({data:menusData}));
                return;
            }
        }

    }
    
    function removeCaterer()
    {
        var caterer = getSelectedCaterer();
        if(null == caterer)
        {
            alert('You have to select an caterer');
            return;
        }

        // locate the index of the element in the master menu array                
        var caterer_id = caterersGrid.store.getValues( caterer, 'id' );

        removeMenusForCaterer(caterer_id);

        caterersGrid.store.deleteItem(caterer);

        // now deselect all of the caterers in the menu
        caterersGrid.selection.clear();
    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////

    function formatMenuNameInfo( menu )
    {
        var str  = '<strong><span style="font-size:12pt">'+menu.name+'</span></strong><br>';
        str = str + menu.description;
        return str;
    }

    function formatMenuPriceInfo( menu )
    {
        var str = '<strong><span style="font-size:10pt">$'+menu.price+' per '+menu.units+'</strong></span>';
        return str;
    }

    function getSelectedMenu()
    {
        var items = menusGrid.selection.getSelected();
        if(items.length<1) return null;
        return items[0];
    }
    
    function showNewMenuForm()
    {
        // get form
        var menuForm = dijit.byId("menuForm");
        menuForm.execute = addNewMenu;

        // make sure contents are empty
        dijit.byId("menu_name").attr('value','');
        dijit.byId("menu_description").attr('value','');
        dijit.byId("menu_units").attr('value','');
        dijit.byId("menu_cost").attr('value','');

        menuForm.show();
    }

    function showEditMenuForm()
    {
        // get selected caterer
        // get caterer form
        var menuForm = dijit.byId("menuForm");
        menuForm.execute = updateMenu;

        // fill caterer fields with field values from selected caterer
        var menu = getSelectedMenu();
        if(null == menu)
        {
            alert('You must select a menu first');
            return;
        }

        var menu_name = menusGrid.store.getValues(menu, 'name');
        var menu_description = menusGrid.store.getValues(menu, 'description');
        var menu_units = menusGrid.store.getValues(menu, 'units');
        var menu_cost = menusGrid.store.getValues(menu, 'price');

        dijit.byId("menu_name").attr('value',menu_name);
        dijit.byId("menu_description").attr('value',menu_description);
        dijit.byId("menu_units").attr('value',menu_units);
        dijit.byId("menu_cost").attr('value',menu_cost);

        menuForm.show();
    }

    function getNewMenuId()
    {
        // loop through caterers and contained menus to get largest menu id
        // and return that number + 1
        var ii;
        var maxId = -1;
        for( ii=0; ii < menusMasterArray.length; ii++ )
        {
            for( var jj=0; jj < menusMasterArray[ii].menus.length; jj++ )
            {
                if(maxId < menusMasterArray[ii].menus[jj].id)
                    maxId = menusMasterArray[ii].menus[jj].id;
            }
        }

        return maxId+1;
    }
    
    function addNewMenu()
    {
        // to insert this record into the appropriate place in the list, will need
        // to get the menu array for caterer_id (e.g. caterer) and assign it to
        // the menu data store.
        newId = getNewMenuId();
        
        var menu = {};

        menu.id = newId;
        menu.name = dijit.byId("menu_name").attr('value');
        menu.description = dijit.byId("menu_description").attr('value');
        menu.units = dijit.byId("menu_units").attr('value');
        menu.price = dijit.byId("menu_cost").attr('value');

        // format the fancy cells
        menu.namecell = formatMenuNameInfo( menu );
        menu.pricecell = formatMenuPriceInfo( menu );
        
        // insert.
        var menusGrid = dijit.byId('menusGrid');
        menusGrid.store.newItem( menu );
        dumpMenus();
    }

    function updateMenu()
    {
        var menu_name = dijit.byId("menu_name").attr('value');
        var menu_description = dijit.byId("menu_description").attr('value');
        var menu_units = dijit.byId("menu_units").attr('value');
        var menu_cost = dijit.byId("menu_cost").attr('value');

        var menu = getSelectedMenu();
        
        menusGrid.store.setValue( menu, 'name', menu_name );
        menusGrid.store.setValue( menu, 'description', menu_description );
        menusGrid.store.setValue( menu, 'units', menu_units );
        menusGrid.store.setValue( menu, 'price', menu_cost );
        
        var menu_namecell = formatMenuNameInfo( menu );
        var menu_pricecell = formatMenuPriceInfo( menu );

        menusGrid.store.setValue( menu, 'namecell', menu_namecell );
        menusGrid.store.setValue( menu, 'pricecell', menu_pricecell );

        menusGrid.store.fetch();
        menusGrid.update();
    }

    function removeMenu()
    {
        var menu = getSelectedMenu();
        if(null == menu)
        {
            alert("You must select a menu first");
        }
        // hope this works and doesn't blow chow...'
        menusGrid.store.deleteItem(menu);
        menusGrid.store.fetch();
        menusGrid.update();
    }

    function dumpCaterers()
    {
        for( var i=0; i < caterersMasterArray.length; i++ )
        {
            console.log('id:' + caterersMasterArray[i].id );
            console.log('name:' + caterersMasterArray[i].name );
        }
    }

    function dumpMenus()
    {
        for( var ii=0; ii < menusMasterArray.length; ii++ )
        {
            console.log('caterer id:'+menusMasterArray[ii].caterer_id)
            for( var jj=0; jj < menusMasterArray[ii].menus.length; jj++ )
            {
                console.log('menu name:'+menusMasterArray[ii].menus[jj].name);
            }
        }
    }

    function caterersToXML()
    {
        var str = '<caterers>';
        for( var i=0; i < caterersMasterArray.length; i++ )
        {
            str = str + '<caterer>';
            str = str + '<id>' + caterersMasterArray[i].id + '</id>';
            str = str + '<name>' + caterersMasterArray[i].name + '</name>';
            str = str + '<address>' + caterersMasterArray[i].address + '</address>';
            str = str + '<city>' + caterersMasterArray[i].city + '</city>';
            str = str + '<state>' + caterersMasterArray[i].state + '</state>';
            str = str + '<zip>' + caterersMasterArray[i].zip + '</zip>';
            str = str + '<phone>' + caterersMasterArray[i].phone + '</phone>';
            str = str + '<fax>' + caterersMasterArray[i].fax + '</fax>';
            str = str + '<email>' + caterersMasterArray[i].email + '</email>';
            str = str + '</caterer>';
        }
        str = str + '</caterers>';
        return str;
    }

    function menusToXML()
    {
        var str = '<caterer_menus>';
        for( var ii=0; ii < menusMasterArray.length; ii++ )
        {
            str = str + '<caterer>';
            str = str + '<id>' + menusMasterArray[ii].id + '</id>';
            str = str + '<menus>';
            for( var jj=0; jj < menusMasterArray[ii].menus.length; jj++ )
            {
                str = str + '<menu>';
                str = str + '<name>' + menusMasterArray[ii].menus[jj].name + '</name>';
                str = str + '<description>' + menusMasterArray[ii].menus[jj].description + '</description>';
                str = str + '<units>' + menusMasterArray[ii].menus[jj].units + '</units>';
                str = str + '<price>' + menusMasterArray[ii].menus[jj].price + '</price>';
                str = str + '</menu>';
            }
            str = str + '</menus>';
            str = str + '</caterer>';
        }
        str = str + '</caterer_menus>';
        return str;
    }

    function caterersAndMenusToXML()
    {
        var str = '<caterers>';
        for( var i=0; i < caterersMasterArray.length; i++ )
        {
            str = str + '<caterer>';
            str = str + '<id>' + caterersMasterArray[i].id + '</id>';
            str = str + '<name>' + caterersMasterArray[i].name + '</name>';
            str = str + '<address>' + caterersMasterArray[i].address + '</address>';
            str = str + '<city>' + caterersMasterArray[i].city + '</city>';
            str = str + '<state>' + caterersMasterArray[i].state + '</state>';
            str = str + '<zip>' + caterersMasterArray[i].zip + '</zip>';
            str = str + '<phone>' + caterersMasterArray[i].phone + '</phone>';
            str = str + '<fax>' + caterersMasterArray[i].fax + '</fax>';
            str = str + '<email>' + caterersMasterArray[i].email + '</email>';
			
			str = str + '<menus>';
			var menus = getMenusForCaterer( caterersMasterArray[i].id );
			for( var j=0; j < menus.length; j++ )
			{
                str = str + '<menu>';
                str = str + '<name>' + menus[j].name + '</name>';
                str = str + '<description>' + menus[j].description + '</description>';
                str = str + '<units>' + menus[j].units + '</units>';
                str = str + '<price>' + menus[j].price + '</price>';
                str = str + '</menu>';
			}
			str = str + '</menus>';
			
            str = str + '</caterer>';
        }
        str = str + '</caterers>';
		return str;
    }

    function onSubmit()
    {
        var str = caterersAndMenusToXML();
		// set caterers = str
		var hidden = document.getElementById('caterersmenus_xml');
		hidden.value = str;
        return false;
    }

    var caterersStore =  new dojo.data.ItemFileWriteStore({data:catererData});
    var menusStore =  new dojo.data.ItemFileWriteStore({data:menusData});

    dojo.addOnLoad( function() {

    catererDlg = dijit.byId("catererForm");

    dojo.connect(dijit.byId("btnNewCaterer"), "onClick", showNewCatererForm );
    dojo.connect(dijit.byId("btnEditCaterer"), "onClick", showEditCatererForm );

    dojo.connect(dijit.byId("btnNewMenu"), "onClick", showNewMenuForm );
    dojo.connect(dijit.byId("btnEditMenu"), "onClick", showEditMenuForm );

    caterersGrid = dijit.byId('caterersGrid');
    menusGrid = dijit.byId('menusGrid');

    dojo.connect( caterersGrid, "onRowClick", catererSelected );

       // caterersGrid.startup();
        //menusGrid.startup();
});
